import {
	INIT_BUYCART,
	CLEAR_CART,
	CONFIRM_REMARK
} from './mutation-types.js'
import * as types from '../types'
import {setStore, getStore} from '@/config/mUtils'

export default {
	// 获取所有分类商品信息
	[types.GET_PRODUCT_LIST](state,payload){
		state.productAll = payload
	},
	// 加入购物车
	[types.ADD_TO_CART](state,{id,categoryType,shopId}) {
		const record = state.added.find(p=>p.id === id)
		if(!record){
			state.added.push({
				id,
				shopId,
				categoryType,
				num:1
			})
			
		}else{
			record.num++
		}
		//存入localStorage
		setStore('buyCart', state.added)
	},
	// 移出购物车
	[types.REMOVE_TO_CART](state, {
		id,
		categoryType
	}) {
		// 查找记录并移除购物车 vuex
		let record = state.added.find(p=>p.id === id)
		if(record){
			record.num--
			if(record.num<=0){
				//  过滤并返回一个新数组
				var newArr = state.added.filter(function(obj){
					return record.id !== obj.id;
				});
				state.added = newArr
			}
		}else{
			record = null
		}
		setStore('buyCart', state.added)
	},
	//网页初始化时从本地缓存获取购物车数据
	[INIT_BUYCART](state,id) {
		// 判断是否店铺id 跟缓存的对的上   如果对不上清空vuex内的数据
		let initCart = getStore('buyCart')
		if (initCart) {
			let cart = JSON.parse(initCart)
			let newArr = cart.filter((obj)=>{
				return id === obj.shopId
			})
			if(newArr){
				state.added = newArr
			}else{
				state.added = []
			}
		}else{
			state.added = []
		}
	},
	//清空当前商品的购物车信息
	[CLEAR_CART](state) {
		state.added = []
		setStore('buyCart', state.added)
	},
	// 商品备注信息
	[CONFIRM_REMARK](state, {
		remarkText,
		inputText
	}) {
		state.remarkText = remarkText;
		state.inputText = inputText;
	},
	[types.INIT_CART_INFO](state,{payload}){
		if(payload.length>0){
			state.added = payload
		}else{
			state.added = []
		}
	},
	// 商家信息
	[types.SHOP_INFO](state,payload){
		if(payload){
			state.shopInfo = payload
		}
	},
	// 用餐人数
	[types.SET_NUM](state,payload){
		if(payload.length>0){
			state.num1[0] = payload[0] 
		}
	},
	// 获取卡券信息
	[types.SET_COUPON](state,payload){
		if(payload){
			state.coupon = payload
		}
	}
}
